Router.onHistoryChange   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 4
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
import {Observer} from '@enbock/state-value-observer/ValueObserver';
2
3
export interface PageData {
4
  name: string,
5
  baseUrl: string
6
  currentUrl: string
7
}
8
9
export default class Router {
10
  currentPage: Observer<PageData | null>;
11
  history: History;
12
13
  constructor(pageObserver: Observer<PageData | null>, history: History) {
14 5
    this.currentPage = pageObserver;
15 5
    this.history = history;
16
  }
17
18
  attachTo(window: Window) {
19 2
    window.addEventListener('popstate', this.onHistoryChange.bind(this));
20
  }
21
22
  initialize(): void {
23 2
    if (this.currentPage.value == null) return;
24 1
    const firstPage: PageData = this.currentPage.value;
25 1
    this.history.replaceState(firstPage, firstPage.name, firstPage.baseUrl);
26 1
    this.updatePage(firstPage);
27
  }
28
29
  changePage(newPage: PageData): void {
30 2
    const currentPage: PageData | null = this.currentPage.value;
31 4
    if (currentPage != null && currentPage.name == newPage.name) {
32 1
      return;
33
    }
34
35 1
    this.history.replaceState(newPage, newPage.name, newPage.currentUrl);
36 1
    this.updatePage(newPage);
37
  }
38
39
  protected updatePage(page: PageData): void {
40 3
    this.currentPage.value = page;
41
  }
42
43
  protected onHistoryChange(event: PopStateEvent): void {
44 1
    const newPage: PageData = event.state as PageData;
45 1
    this.updatePage(newPage);
46
  }
47
}
48